<template>
  <div class="attendance-batch">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('attendance.batch') }}</span>
      </div>
      
      <!-- 搜索条件 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item :label="$t('course.title')">
            <el-select v-model="searchForm.courseId" :placeholder="$t('common.pleaseSelect') + ' ' + $t('course.title')" clearable @change="getCourseStudents">
              <el-option 
                v-for="course in courses" 
                :key="course.id" 
                :label="course.name" 
                :value="course.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('common.date')">
            <el-date-picker
              v-model="searchForm.date"
              type="date"
              :placeholder="$t('common.pleaseSelect') + ' ' + $t('common.date')"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchStudents">{{ $t('common.search') }}</el-button>
            <el-button @click="resetSearch">{{ $t('common.reset') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 批量操作 -->
      <div class="batch-actions" v-if="students.length > 0">
        <el-button type="primary" @click="batchCheckIn">{{ $t('attendance.batchMarkNormal') }}</el-button>
        <el-button type="warning" @click="batchLate">{{ $t('attendance.batchMarkLate') }}</el-button>
        <el-button type="danger" @click="batchAbsent">{{ $t('attendance.batchMarkAbsent') }}</el-button>
      </div>
      
      <!-- 学生列表 -->
      <div class="student-list" v-loading="loading">
        <el-table
          ref="table"
          :data="students"
          border
          style="width: 100%"
          :empty-text="$t('el.table.emptyText')"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column prop="id" :label="$t('user.id')" width="80"></el-table-column>
          <el-table-column prop="name" :label="$t('attendance.studentName')" width="120"></el-table-column>
          <el-table-column prop="groupName" :label="$t('group.title')" width="120"></el-table-column>
          <el-table-column prop="telephone" :label="$t('user.telephone')" width="150"></el-table-column>
          <el-table-column prop="attendanceStatus" :label="$t('attendance.status')" width="120">
            <template slot-scope="scope">
              <el-tag :type="getStatusType(scope.row.attendanceStatus)">
                {{ getStatusText(scope.row.attendanceStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="checkInTime" :label="$t('attendance.checkTime')" width="180"></el-table-column>
          <el-table-column :label="$t('common.operation')" width="300" v-if="!isMobile">
            <template slot-scope="scope">
              <el-button 
                type="success" 
                size="mini" 
                @click="handleCheckIn(scope.row)"
                :disabled="scope.row.attendanceStatus !== null">
                {{ $t('attendance.normal') }}
              </el-button>
              <el-button 
                type="warning" 
                size="mini" 
                @click="handleLate(scope.row)"
                :disabled="scope.row.attendanceStatus !== null">
                {{ $t('attendance.late') }}
              </el-button>
              <el-button 
                type="danger" 
                size="mini" 
                @click="handleAbsent(scope.row)"
                :disabled="scope.row.attendanceStatus !== null">
                {{ $t('attendance.absent') }}
              </el-button>
            </template>
          </el-table-column>
          <!-- 移动端操作列 -->
          <el-table-column :label="$t('common.operation')" width="95" fixed="right" v-if="isMobile">
            <template slot-scope="scope">
              <el-popover
                placement="left"
                width="120"
                trigger="click">
                <div class="mobile-operation-buttons">
                  <el-button 
                    type="success" 
                    size="mini" 
                    @click="handleCheckIn(scope.row)"
                    :disabled="scope.row.attendanceStatus !== null">
                    {{ $t('attendance.normal') }}
                  </el-button>
                  <el-button 
                    type="warning" 
                    size="mini" 
                    @click="handleLate(scope.row)"
                    :disabled="scope.row.attendanceStatus !== null">
                    {{ $t('attendance.late') }}
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="mini" 
                    @click="handleAbsent(scope.row)"
                    :disabled="scope.row.attendanceStatus !== null">
                    {{ $t('attendance.absent') }}
                  </el-button>
                </div>
                <el-button slot="reference" type="primary" size="mini">
                  {{ $t('common.operation') }} <i class="el-icon-arrow-down"></i>
                </el-button>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 批量操作对话框 -->
      <el-dialog :title="batchDialogTitle" :visible.sync="batchDialogVisible" width="500px" :fullscreen="isMobile">
        <el-form :model="batchForm" label-width="100px">
          <el-form-item :label="$t('attendance.status')">
            <el-tag :type="getStatusType(batchForm.status)">{{ getStatusText(batchForm.status) }}</el-tag>
          </el-form-item>
          <el-form-item :label="$t('common.remark')">
            <el-input type="textarea" v-model="batchForm.remark" :rows="3" :placeholder="$t('common.pleaseEnter') + ' ' + $t('common.remark')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('attendance.selectedStudents')">
            <div class="selected-students">
              <el-tag v-for="student in selectedStudents" :key="student.id" style="margin-right: 5px; margin-bottom: 5px;">
                {{ student.name }}
              </el-tag>
            </div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="batchDialogVisible = false">{{ $t('common.cancel') }}</el-button>
          <el-button type="primary" @click="submitBatch" :loading="submitLoading">{{ $t('common.confirm') }}</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "AttendanceBatch",
  data() {
    return {
      userInfo: JSON.parse(sessionStorage.getItem("userInfo")),
      isTeacher: false,
      isAdmin: false,
      loading: false,
      submitLoading: false,
      
      // 搜索表单
      searchForm: {
        courseId: null,
        date: new Date().toISOString().split('T')[0] // 默认今天
      },
      
      // 课程列表
      courses: [],
      
      // 学生列表
      students: [],
      
      // 选中的学生
      selectedStudents: [],
      
      // 批量操作对话框
      batchDialogVisible: false,
      batchDialogTitle: '批量签到',
      batchForm: {
        courseId: null,
        date: null,
        status: 0,
        remark: '',
        studentIds: []
      },
      
      isMobile: false,
      screenWidth: document.body.clientWidth
    }
  },
  created() {
    this.checkUserRole();
    this.initData();
    this.checkScreenSize();
  },
  mounted() {
    window.addEventListener('resize', this.handleResize);
    this.checkScreenSize();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    handleResize() {
      this.screenWidth = document.body.clientWidth;
      this.checkScreenSize();
    },
    checkScreenSize() {
      this.isMobile = this.screenWidth < 768;
    },
    checkUserRole() {
      // 检查用户角色
      if (this.userInfo && this.userInfo.roleName) {
        this.isTeacher = this.userInfo.roleName.includes('teacher');
        this.isAdmin = this.userInfo.roleName.includes('admin');
      }
    },
    initData() {
      // 获取课程列表
      this.getCourses();
    },
    getCourses() {
      const userId = this.userInfo.userId;
      let url = this.isAdmin ? '/course/page' : `/course/teacher/${userId}`;
      
      this.$axios.get(url).then(res => {
        if (res.code === 200) {
          if (this.isAdmin) {
            this.courses = res.data.records || [];
          } else {
            this.courses = res.data || [];
          }
          
          // 如果只有一个课程，自动选择
          if (this.courses.length === 1) {
            this.searchForm.courseId = this.courses[0].id;
            this.getCourseStudents();
          }
        }
      }).catch(err => {
        console.error('获取课程列表失败', err);
        this.$message.error('获取课程列表失败');
      });
    },
    getCourseStudents() {
      if (!this.searchForm.courseId) {
        this.students = [];
        return;
      }
      
      this.loading = true;
      
      this.$axios.get(`/course/${this.searchForm.courseId}/students`).then(res => {
        if (res.code === 200) {
          // 直接使用返回的数据数组
          const students = res.data || [];
          
          // 获取班级信息
          const groupIds = [...new Set(students.map(s => s.groupId).filter(id => id))];
          if (groupIds.length > 0) {
            this.$axios.get('/group/list').then(groupRes => {
              if (groupres.code === 200) {
                const groups = groupres.data || [];
                // 将班级信息添加到学生数据中
                this.students = students.map(student => {
                  const group = groups.find(g => g.id === student.groupId);
                  const updatedStudent = {
                    ...student,
                    groupName: group ? group.name : '未分配班级',
                    attendanceStatus: null,
                    checkInTime: null
                  };
                  return updatedStudent;
                });
              } else {
                this.initStudents(students);
              }
              
              // 如果有日期，查询当天考勤记录
              if (this.searchForm.date) {
                this.getAttendanceRecords();
              }
            }).catch(err => {
              console.error('获取班级信息失败', err);
              this.initStudents(students);
            });
          } else {
            this.initStudents(students);
          }
        } else {
          this.$message.error(res.data.msg || '获取课程学生失败');
        }
      }).catch(err => {
        console.error('获取课程学生失败', err);
        this.$message.error('获取课程学生失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    
    // 初始化学生考勤状态
    initStudents(students) {
      this.students = students.map(student => ({
        ...student,
        groupName: this.$t('group.unassigned'),
        attendanceStatus: null,
        checkInTime: null
      }));
      
      // 如果有日期，查询当天考勤记录
      if (this.searchForm.date) {
        this.getAttendanceRecords();
      }
    },
    getAttendanceRecords() {
      if (!this.searchForm.courseId || !this.searchForm.date || this.students.length === 0) {
        return;
      }
      
      this.loading = true;
      
      const params = {
        courseId: this.searchForm.courseId,
        startDate: this.searchForm.date,
        endDate: this.searchForm.date
      };
      
      this.$axios.get('/attendance/page', { params }).then(res => {
        if (res.code === 200) {
          const records = res.data.records || [];
          
          // 更新学生考勤状态
          this.students.forEach(student => {
            const record = records.find(r => r.userId === student.id);
            if (record) {
              student.attendanceStatus = record.status;
              student.checkInTime = new Date(record.checkInTime).toLocaleString();
              student.recordId = record.id;
            } else {
              student.attendanceStatus = null;
              student.checkInTime = null;
              student.recordId = null;
            }
          });
        } else {
          this.$message.error(res.data.msg || '获取考勤记录失败');
        }
      }).catch(err => {
        console.error('获取考勤记录失败', err);
        this.$message.error('获取考勤记录失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    searchStudents() {
      if (!this.searchForm.courseId) {
        this.$message.warning(this.$t('attendance.pleaseSelectCourse'));
        return;
      }
      
      if (!this.searchForm.date) {
        this.$message.warning(this.$t('attendance.pleaseSelectDate'));
        return;
      }
      
      this.getCourseStudents();
    },
    resetSearch() {
      this.searchForm = {
        courseId: null,
        date: new Date().toISOString().split('T')[0]
      };
      this.students = [];
    },
    handleSelectionChange(val) {
      this.selectedStudents = val;
    },
    getStatusType(status) {
      if (status === null) return '';
      
      const types = {
        0: 'success',
        1: 'warning',
        2: 'info',
        3: 'danger'
      };
      return types[status] || '';
    },
    getStatusText(status) {
      if (status === null) return this.$t('attendance.notCheckedIn');
      
      const texts = {
        0: this.$t('attendance.normal'),
        1: this.$t('attendance.late'),
        2: this.$t('attendance.earlyLeave'),
        3: this.$t('attendance.absent')
      };
      return texts[status] || this.$t('common.unknown');
    },
    handleCheckIn(student) {
      this.createAttendanceRecord(student, 0);
    },
    handleLate(student) {
      this.createAttendanceRecord(student, 1);
    },
    handleAbsent(student) {
      this.createAttendanceRecord(student, 3);
    },
    createAttendanceRecord(student, status) {
      this.loading = true;
      
      let remarkText = '';
      if (status === 0) {
        remarkText = this.$t('attendance.teacherCheckIn');
      } else if (status === 1) {
        remarkText = this.$t('attendance.teacherMarkLate');
      } else {
        remarkText = this.$t('attendance.teacherMarkAbsent');
      }
      
      const params = {
        userId: student.id,
        courseId: this.searchForm.courseId,
        status: status,
        remark: remarkText,
        locationLatitude: null,
        locationLongitude: null
      };
      
      this.$axios.post('/attendance/record', params).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t('common.operationSuccess'));
          // 更新学生考勤状态
          student.attendanceStatus = status;
          student.checkInTime = new Date().toLocaleString();
          // 刷新获取完整记录信息
          this.getAttendanceRecords();
        } else {
          this.$message.error(res.data.msg || this.$t('common.operationFailed'));
        }
      }).catch(err => {
        console.error('操作失败', err);
        this.$message.error(this.$t('common.operationFailed'));
      }).finally(() => {
        this.loading = false;
      });
    },
    batchCheckIn() {
      if (this.selectedStudents.length === 0) {
        this.$message.warning(this.$t('attendance.pleaseSelectStudents'));
        return;
      }
      
      this.batchDialogTitle = this.$t('attendance.batchMarkNormal');
      this.batchForm = {
        courseId: this.searchForm.courseId,
        date: this.searchForm.date,
        status: 0,
        remark: this.$t('attendance.teacherBatchCheckIn'),
        studentIds: this.selectedStudents.map(s => s.id)
      };
      this.batchDialogVisible = true;
    },
    batchLate() {
      if (this.selectedStudents.length === 0) {
        this.$message.warning(this.$t('attendance.pleaseSelectStudents'));
        return;
      }
      
      this.batchDialogTitle = this.$t('attendance.batchMarkLate');
      this.batchForm = {
        courseId: this.searchForm.courseId,
        date: this.searchForm.date,
        status: 1,
        remark: this.$t('attendance.teacherBatchMarkLate'),
        studentIds: this.selectedStudents.map(s => s.id)
      };
      this.batchDialogVisible = true;
    },
    batchAbsent() {
      if (this.selectedStudents.length === 0) {
        this.$message.warning(this.$t('attendance.pleaseSelectStudents'));
        return;
      }
      
      this.batchDialogTitle = this.$t('attendance.batchMarkAbsent');
      this.batchForm = {
        courseId: this.searchForm.courseId,
        date: this.searchForm.date,
        status: 3,
        remark: this.$t('attendance.teacherBatchMarkAbsent'),
        studentIds: this.selectedStudents.map(s => s.id)
      };
      this.batchDialogVisible = true;
    },
    submitBatch() {
      if (this.selectedStudents.length === 0) {
        this.$message.warning(this.$t('attendance.pleaseSelectStudents'));
        return;
      }
      
      this.submitLoading = true;
      
      const params = {
        courseId: this.batchForm.courseId,
        status: this.batchForm.status,
        remark: this.batchForm.remark,
        userIds: this.batchForm.studentIds
      };
      
      this.$axios.post('/attendance/batch', params).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t('attendance.batchOperationSuccess'));
          this.batchDialogVisible = false;
          
          // 更新学生考勤状态
          this.selectedStudents.forEach(student => {
            student.attendanceStatus = this.batchForm.status;
            student.checkInTime = new Date().toLocaleString();
          });
          
          // 清空选中
          this.$refs.table.clearSelection();
          this.selectedStudents = [];
          
          // 刷新获取完整记录信息
          this.getAttendanceRecords();
        } else {
          this.$message.error(res.data.msg || this.$t('attendance.batchOperationFailed'));
        }
      }).catch(err => {
        console.error('批量操作失败', err);
        this.$message.error(this.$t('attendance.batchOperationFailed'));
      }).finally(() => {
        this.submitLoading = false;
      });
    }
  }
}
</script>

<style scoped>
.attendance-batch {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
}

.batch-actions {
  margin-bottom: 20px;
}

.student-list {
  margin-top: 20px;
}

.selected-students {
  max-height: 100px;
  overflow-y: auto;
}

.mobile-operation-buttons {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.mobile-operation-buttons .el-button {
  margin-left: 0;
  margin-bottom: 8px;
  width: 100%;
  text-align: left;
}

.mobile-operation-buttons .el-button:last-child {
  margin-bottom: 0;
}

@media screen and (max-width: 768px) {
  .search-container .el-form-item {
    display: block;
    width: 100%;
    margin-right: 0;
  }

  .search-container .el-select, 
  .search-container .el-date-editor {
    width: 100%;
  }

  .el-table {
    width: 100%;
    font-size: 12px;
  }
  
  .el-button {
    padding: 7px 10px;
    font-size: 12px;
  }

  .batch-actions {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .batch-actions .el-button {
    margin-left: 0;
  }
}
</style> 